import sys
import random
import pandas as pd
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QHBoxLayout, QLabel, QPushButton, QStyleOption, QStyle
from PyQt5.QtGui import QPixmap, QPainter, QIcon, QBrush
from PyQt5.QtCore import Qt

# 定义图片路径常量
IMG_DIR = 'img'
EMPTY_IMG = f'{IMG_DIR}/横杠.png'
QIAN_IMG = f'{IMG_DIR}/乾.png'
KUN_IMG = f'{IMG_DIR}/坤.png'
SINGLE_START_IMG = f'{IMG_DIR}/一键起卦.png'
TRADITIONAL_START_IMG = f'{IMG_DIR}/传统起卦.png'
BACKGROUND_IMG = f'{IMG_DIR}/底图.png'
BUTTON_IMG = f'{IMG_DIR}/按钮.png'


class ImageButtonWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.image_labels = []
        self.data_labels = ["卦名", "卦象等级", "卦词", "推断", "大象", "运势", "爱情", "疾病", "失物", "诉讼"]
        self.value_labels = []
        self.codes = []
        self.click_count = 0
        self.buttons = []
        self.top_button_1 = None
        self.top_button_2 = None
        self.initUI()
        try:
            self.df = pd.read_excel('六十四卦.xlsx', dtype={'编码': str})
        except FileNotFoundError:
            print("未找到 '六十四卦.xlsx' 文件，请确保该文件与代码在同一目录下。")
            self.df = None

    def initUI(self):
        self.setGeometry(100, 100, 350, 600)
        self.setWindowTitle('窥探天机')

        main_layout = QVBoxLayout()

        # 创建顶部按钮布局
        top_button_layout = QHBoxLayout()

        self.top_button_1 = QPushButton(self)
        pixmap_1 = QPixmap(SINGLE_START_IMG)
        scaled_pixmap_1 = pixmap_1.scaled(100, 25, Qt.KeepAspectRatio, Qt.SmoothTransformation)
        icon_1 = QIcon(scaled_pixmap_1)
        self.top_button_1.setIcon(icon_1)
        self.top_button_1.setIconSize(scaled_pixmap_1.size())
        self.top_button_1.setFixedSize(100, 25)
        self.top_button_1.clicked.connect(self.generate_numbers_all)
        top_button_layout.addWidget(self.top_button_1)

        self.top_button_2 = QPushButton(self)
        pixmap_2 = QPixmap(TRADITIONAL_START_IMG)
        scaled_pixmap_2 = pixmap_2.scaled(100, 25, Qt.KeepAspectRatio, Qt.SmoothTransformation)
        icon_2 = QIcon(scaled_pixmap_2)
        self.top_button_2.setIcon(icon_2)
        self.top_button_2.setIconSize(scaled_pixmap_2.size())
        self.top_button_2.setFixedSize(100, 25)
        # 将传统起卦按钮的点击信号连接到空函数
        self.top_button_2.clicked.connect(self.do_nothing)
        top_button_layout.addWidget(self.top_button_2)

        main_layout.addLayout(top_button_layout)

        for _ in range(6):
            row_layout = QHBoxLayout()

            image_label = QLabel(self)
            pixmap = QPixmap(EMPTY_IMG)
            scaled_pixmap = pixmap.scaled(175, 25)
            image_label.setPixmap(scaled_pixmap)
            row_layout.addWidget(image_label)
            self.image_labels.append(image_label)

            button = QPushButton(self)
            # 设置按钮图片
            button_pixmap = QPixmap(BUTTON_IMG)
            scaled_button_pixmap = button_pixmap.scaled(25, 25, Qt.KeepAspectRatio, Qt.SmoothTransformation)
            button_icon = QIcon(scaled_button_pixmap)
            button.setIcon(button_icon)
            button.setIconSize(scaled_button_pixmap.size())
            button.setFixedSize(25, 25)
            button.clicked.connect(lambda _, lbl=image_label, btn=button: self.generate_numbers_single(lbl, btn))
            row_layout.addWidget(button)
            self.buttons.append(button)

            main_layout.addLayout(row_layout)

        self.code_label = QLabel(self)
        main_layout.addWidget(self.code_label)

        for label_text in self.data_labels:
            row_layout = QHBoxLayout()
            label = QLabel(label_text + ":", self)
            value = QLabel("", self)
            value.setWordWrap(True)
            label.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
            value.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
            row_layout.addWidget(label, stretch=1)
            row_layout.addWidget(value, stretch=3)
            main_layout.addLayout(row_layout)
            self.value_labels.append(value)

        self.setLayout(main_layout)

        # 设置背景图片
        background_pixmap = QPixmap(BACKGROUND_IMG)
        scaled_background_pixmap = background_pixmap.scaled(self.size(), Qt.IgnoreAspectRatio, Qt.SmoothTransformation)
        background_brush = QBrush(scaled_background_pixmap)
        palette = self.palette()
        palette.setBrush(self.backgroundRole(), background_brush)
        self.setPalette(palette)

    def paintEvent(self, event):
        opt = QStyleOption()
        opt.initFrom(self)
        painter = QPainter(self)
        self.style().drawPrimitive(QStyle.PE_Widget, opt, painter, self)

    def generate_numbers_single(self, label, button):
        if self.click_count == 0:
            self.top_button_1.hide()
            self.top_button_2.hide()

        numbers, total, code, pixmap = self.generate_random_code()
        scaled_pixmap = pixmap.scaled(175, 25)
        label.setPixmap(scaled_pixmap)
        print(f"生成的数字: {numbers}，总和: {total}，编码: {code}")
        self.codes.append(code)
        self.click_count += 1
        button.hide()

        if self.click_count == 6:
            full_code = ''.join(self.codes)
            print(f"组合编码: {full_code}")
            self.code_label.setText(f"组合编码: {full_code}")
            if self.df is not None:
                self.display_data_from_excel(full_code)
            self.codes = []
            self.click_count = 0
            self.top_button_1.show()
            self.top_button_2.show()
            for btn in self.buttons:
                btn.show()

    def generate_numbers_all(self):
        self.codes = []
        for label, btn in zip(self.image_labels, self.buttons):
            numbers, total, code, pixmap = self.generate_random_code()
            scaled_pixmap = pixmap.scaled(175, 25)
            label.setPixmap(scaled_pixmap)
            print(f"生成的数字: {numbers}，总和: {total}，编码: {code}")
            self.codes.append(code)

        full_code = ''.join(self.codes)
        print(f"组合编码: {full_code}")
        self.code_label.setText(f"组合编码: {full_code}")
        if self.df is not None:
            self.display_data_from_excel(full_code)
        self.codes = []

    def generate_random_code(self):
        numbers = [random.choice([2, 3]) for _ in range(3)]
        total = sum(numbers)
        if total in [7, 9]:
            pixmap = QPixmap(QIAN_IMG)
            code = '0'
        elif total in [6, 8]:
            pixmap = QPixmap(KUN_IMG)
            code = '1'
        return numbers, total, code, pixmap

    def display_data_from_excel(self, code):
        result = self.df[self.df['编码'] == code]
        if not result.empty:
            row = result.iloc[0]
            for i, label_text in enumerate(self.data_labels):
                if label_text in row:
                    text = str(row[label_text])
                    if len(text) > 20 and label_text in ["推断", "大象", "运势", "爱情", "疾病", "失物", "诉讼"]:
                        mid_index = len(text) // 2
                        text = text[:mid_index] + '\n' + text[mid_index:]
                    self.value_labels[i].setText(text)
        else:
            print(f"未找到编码为 {code} 的数据。")

    def do_nothing(self):
        # 空函数，不做任何处理
        pass


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = ImageButtonWindow()
    window.show()
    sys.exit(app.exec_())
